
package net.ib.mtalk.database.helper;

import java.util.List;
import java.util.UUID;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.FileKey;
import net.ib.mntalk.protocol.Common.Message;
import net.ib.mntalk.protocol.Common.ReadMark;
import net.ib.mntalk.protocol.Common.UUIDMsg;
import net.ib.mntalk.protocol.Common.UserMessage;
import net.ib.mntalk.protocol.Session.SendMessageReq;
import net.ib.mntalk.protocol.Session.SendMessageRes;
import net.ib.mntalk.protocol.client.Database.FileTransferInfo;
import net.ib.mtalk.constant.MTalkConstant;
import net.ib.mtalk.database.DatabaseContract.MessageTable;
import net.ib.mtalk.database.DatabaseContract.ViewTable;
import net.ib.mtalk.database.DatabaseContract.MessageTable.MessageObjectType;
import net.ib.mtalk.database.DatabaseContract.MessageTable.MessageProperty;
import net.ib.mtalk.database.DatabaseContract.MessageTable.MessageStatus;
import net.ib.mtalk.database.DatabaseContract.MessageTable.SendMessage;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import net.ib.mtalk.util.NotifyingAsyncQueryHandler;
import net.ib.mtalk.util.TimeAdapter;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.google.protobuf.micro.InvalidProtocolBufferMicroException;

public class ChatDatabaseHelper {

	/** 생성 Create(Insert) **/
	public static void insertSendMessage( Context context,
			UUID clientViewUuid,
			SendMessageReq message, 
			MessageObjectType objectType,
			MessageStatus status,
			SendMessage isSendMessage
			){
		insertSendMessage(context, clientViewUuid, message, objectType, status, isSendMessage, 
				null, null,	null);
	}
	
	public static void insertSendMessage( Context context,
			UUID clientViewUuid,
			SendMessageReq message, 
			MessageObjectType objectType,
			MessageStatus status,
			SendMessage isSendMessage,
			MessageProperty property,
			Uri fileUri,
			UUID clientMsgUuid){
		
		if(clientMsgUuid == null){
			clientMsgUuid = UUID.randomUUID();
		}
		long viewUuidMsb;
		long viewUuidLsb;
		if(message != null){
			viewUuidMsb = GpbSupport.msbOf(message.getViewUuid());
			viewUuidLsb = GpbSupport.lsbOf(message.getViewUuid());
		}else{			
			viewUuidMsb = GpbSupport.msbOf(InboxDatabaseHelper.getViewUUID(context, clientViewUuid));
			viewUuidLsb = GpbSupport.lsbOf(InboxDatabaseHelper.getViewUUID(context, clientViewUuid));
		}
		ContentValues cv = new ContentValues();
		cv.put(MessageTable.KEY_CLIENT_VIEW_UUID_MSB, clientViewUuid.getMostSignificantBits());
		cv.put(MessageTable.KEY_CLIENT_VIEW_UUID_LSB, clientViewUuid.getLeastSignificantBits());
		cv.put(MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB, clientMsgUuid.getMostSignificantBits());
		cv.put(MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB, clientMsgUuid.getLeastSignificantBits());
		cv.put(MessageTable.KEY_VIEW_UUID_MSB, viewUuidMsb);
		cv.put(MessageTable.KEY_VIEW_UUID_LSB, viewUuidLsb);
		cv.put(MessageTable.KEY_MESSAGE_STATUS, status.ordinal());
		cv.put(MessageTable.KEY_MESSAGE_OBJECT_TYPE, objectType.getCode());
		cv.put(MessageTable.KEY_SEND_MESSAGE, isSendMessage.ordinal());
		cv.put(MessageTable.KEY_MESSAGE_TIME, System.currentTimeMillis());
		cv.put(MessageTable.KEY_MESSAGE_UNREAD_COUNT, InboxDatabaseHelper.getMembersCount(context, clientViewUuid));
		if( message != null ) cv.put(MessageTable.KEY_MESSAGE, message.getMessage().toByteArray());
		if( property!=null ) cv.put(MessageTable.KEY_MESSAGE_PROPERTY, property.ordinal());
		if( fileUri!= null ) cv.put(MessageTable.KEY_FILE_URI, fileUri.toString());
		ContentResolver cr = context.getContentResolver();
		cr.insert(MessageTable.CONTENT_URI, cv);
	}
	
	public static void insertGetMessages(Context context,
			Message message,
			MessageProperty property,
			Uri fileUri,
			UUID clientMsgUuid){
		ContentResolver cr = context.getContentResolver();
		ContentValues cv = setContentValuesForGetMessages(
				InboxDatabaseHelper.getClientUUID(context, message.getViewUuid()), 
				message, property, fileUri, clientMsgUuid);
		cr.insert(MessageTable.CONTENT_URI, cv);
	}
	
	/**
	 * DatabaseHandler로 callback을 받으려면
	 * @param mQueryHandler
	 * @param message - Message
	 * @param status - MessageStatus : 0-SENDING, 1-SERVER_RECEIVE, 2-CLIENT_RECEIVE, 3-SERVER_RECEIVE_FAIL
	 * @param isSendMessage
	 * @param property
	 * @param fileUri
	 */
	public static void insertGetMessagesByDbHandler(NotifyingAsyncQueryHandler dbHandler,
			UUID clientViewUuid,
			Message message, 
			MessageProperty property,
			Uri fileUri,
			UUID clientMsgUuid){
		ContentValues cv = setContentValuesForGetMessages(clientViewUuid, message, property, fileUri, clientMsgUuid);
		dbHandler.startInsert(MessageTable.CONTENT_URI, cv);
	}
	
	/**
	 * 
	 * @param context
	 * @param message
	 */
	public static void insertMessage(Context context, Common.Message message){
		ContentValues cv = new ContentValues();
		UUID clientViewUuid = InboxDatabaseHelper.getClientUUID(context, message.getViewUuid());
		UUID clientMsgUuid = UUID.randomUUID();
		cv.put(MessageTable.KEY_CLIENT_VIEW_UUID_MSB, clientViewUuid.getMostSignificantBits());
		cv.put(MessageTable.KEY_CLIENT_VIEW_UUID_LSB, clientViewUuid.getLeastSignificantBits());
		cv.put(MessageTable.KEY_VIEW_UUID_MSB, GpbSupport.msbOf(message.getViewUuid()));
		cv.put(MessageTable.KEY_VIEW_UUID_LSB, GpbSupport.lsbOf(message.getViewUuid()));
		cv.put(MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB, clientMsgUuid.getMostSignificantBits());
		cv.put(MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB, clientMsgUuid.getLeastSignificantBits());
		cv.put(MessageTable.KEY_MESSAGE_UUID_MSB, GpbSupport.msbOf(message.getMsgUuid()));
		cv.put(MessageTable.KEY_MESSAGE_UUID_LSB, GpbSupport.lsbOf(message.getMsgUuid()));
		cv.put(MessageTable.KEY_MESSAGE_NOTI_UUID_MSB, GpbSupport.msbOf(message.getNotiUuid()));
		cv.put(MessageTable.KEY_MESSAGE_NOTI_UUID_LSB, GpbSupport.lsbOf(message.getNotiUuid()));
		cv.put(MessageTable.KEY_MESSAGE_STATUS, MessageTable.MessageStatus.CLIENT_RECEIVE.ordinal());
		cv.put(MessageTable.KEY_MESSAGE_OBJECT_TYPE, message.getType());
		cv.put(MessageTable.KEY_MESSAGE_TIME, TimeAdapter.getMillisecondFromUUIDMsg(message.getMsgUuid()));
		cv.put(MessageTable.KEY_MESSAGE_UNREAD_COUNT, InboxDatabaseHelper.getMembersCount(context, clientViewUuid));
		switch(message.getType()){
			case Common.MSG_TYPE_USER_MSG:
				UserMessage um = message.getUserMassage();
				if(um.hasSenderUuid()){
					if((GpbSupport.msbOf(um.getSenderUuid()) == GpbSupport.msbOf(GlobalPreferences.getUserUUID())) 
							&& (GpbSupport.lsbOf(um.getSenderUuid()) == GpbSupport.lsbOf(GlobalPreferences.getUserUUID()))){	
						cv.put(MessageTable.KEY_SEND_MESSAGE, MessageTable.SendMessage.YES.ordinal());
					}else{
						cv.put(MessageTable.KEY_SEND_MESSAGE, MessageTable.SendMessage.NO.ordinal());
					}
				}else{			
					cv.put(MessageTable.KEY_SEND_MESSAGE, MessageTable.SendMessage.NO.ordinal());
				}
				cv.put(MessageTable.KEY_MESSAGE, message.getUserMassage().toByteArray());
				if( message.getUserMassage().hasAttachFile() ){
					switch(message.getUserMassage().getAttachFile().getFileType()){
					case Common.FT_PROFILE_IMG:
						break;
					case Common.FT_IMG:
						cv.put(MessageTable.KEY_MESSAGE_PROPERTY, MessageTable.MessageProperty.IMAGE.ordinal());
						break;
					case Common.FT_VIDEO:
						cv.put(MessageTable.KEY_MESSAGE_PROPERTY, MessageTable.MessageProperty.VIDEO.ordinal());
						break;
					case Common.FT_AUDIO:
						cv.put(MessageTable.KEY_MESSAGE_PROPERTY, MessageTable.MessageProperty.RECORD.ordinal());
						break;
					}
				}else if(message.getUserMassage().hasAttachment()){
					if(message.getUserMassage().getAttachment().getMimeType() == MTalkConstant.MIME_TYPE_VCARD){
						cv.put(MessageTable.KEY_MESSAGE_PROPERTY, MessageTable.MessageProperty.CONTACT.ordinal());
					}else if(message.getUserMassage().getAttachment().getMimeType() == MTalkConstant.MIME_TYPE_VCALENDAR){
						cv.put(MessageTable.KEY_MESSAGE_PROPERTY, MessageTable.MessageProperty.CALENDAR.ordinal());
					}else if(message.getUserMassage().getAttachment().getMimeType() == MTalkConstant.MIME_TYPE_GEOTAG){
						cv.put(MessageTable.KEY_MESSAGE_PROPERTY, MessageTable.MessageProperty.GEOTAG.ordinal());
					}else if(message.getUserMassage().getAttachment().getMimeType() == MTalkConstant.MIME_TYPE_GIFT){
						cv.put(MessageTable.KEY_MESSAGE_PROPERTY, MessageTable.MessageProperty.GIFT.ordinal());
					}
				}else{
					cv.put(MessageTable.KEY_MESSAGE_PROPERTY, MessageTable.MessageProperty.TEXT.ordinal());
				}
				break;
			case Common.MSG_TYPE_SYSTEM_MSG:
				cv.put(MessageTable.KEY_SEND_MESSAGE, MessageTable.SendMessage.NO.ordinal());
				cv.put(MessageTable.KEY_MESSAGE, message.getSystemMessage().toByteArray());
				break;
			case Common.MSG_TYPE_CONTROL_MSG:
				cv.put(MessageTable.KEY_SEND_MESSAGE, MessageTable.SendMessage.NO.ordinal());
				cv.put(MessageTable.KEY_MESSAGE, message.getControlMessage().toByteArray());
				break;
		}
		ContentResolver cr = context.getContentResolver();
		cr.insert(MessageTable.CONTENT_URI, cv);
	}
	
	
	
	
	
	
	
	/** 읽기 Read(Query) **/

	/**
	 * 메시지가 있는지 확인. insert 할 것인지 확인한다.
	 */
	public static void syncGetMessages(Context context, Common.Message message){
		if(!existCheckMessage(context, message)){
			insertMessage(context, message);
		}else{
			updateMessage(context, message);
		}
	}
	
	public static boolean existCheckMessage(Context context, Common.Message message){
		ContentResolver cr = context.getContentResolver();
		String[] projection = new String[]{ MessageTable._ID };
		String selection = "(" + MessageTable.KEY_MESSAGE_UUID_MSB + "=? AND "
							+ MessageTable.KEY_MESSAGE_UUID_LSB + "=?)";
		String[] selectionArgs = new String[]{ String.valueOf(GpbSupport.msbOf(message.getMsgUuid())), 
											String.valueOf(GpbSupport.lsbOf(message.getMsgUuid()))};
		Cursor cursor = cr.query(MessageTable.CONTENT_URI, projection, selection, selectionArgs, null);
		boolean exist = false; 
		if(cursor.moveToFirst()){
			exist = true;
		}
		cursor.close();
		return exist;
	}
	
	/**
	 * 파일 경로를 읽어 온다.
	 * @param context
	 * @param messageUuid
	 * @return 파일 경로가 없으면 null 을 리턴한다.
	 */
	public static Uri getFileUri(Context context, UUIDMsg messageUuid){
		ContentResolver cr = context.getContentResolver();
		String selection = MessageTable.KEY_MESSAGE_UUID_MSB+"=? AND "
			+ MessageTable.KEY_MESSAGE_UUID_LSB+"=?";
		String[] selectionArgs = new String[]{
			String.valueOf(GpbSupport.msbOf(messageUuid)), String.valueOf(GpbSupport.lsbOf(messageUuid))};
		Cursor cursor = cr.query(MessageTable.CONTENT_URI, new String[]{MessageTable.KEY_FILE_URI}, 
				selection, selectionArgs, null);
		Uri uri = null;
		if(cursor.moveToFirst()){
			uri = Uri.parse(cursor.getString(cursor.getColumnIndexOrThrow(MessageTable.KEY_FILE_URI)));
		}
		cursor.close();
		return uri;
	}
	
	/**
	 * 파일 전송 정보를 읽어 온다.
	 * @param context
	 * @param messageUuid
	 * @return
	 */
	public static FileTransferInfo getFileTransferInfo(Context context, UUID clientMsgUuid){
		ContentResolver cr = context.getContentResolver();
		String selection;
		String[] selectionArgs;
		selection = MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB+"=? AND "
		+ MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB+"=?";
		selectionArgs = new String[]{String.valueOf(clientMsgUuid.getMostSignificantBits()),
				String.valueOf(clientMsgUuid.getLeastSignificantBits())};
		
		Cursor cursor = cr.query(MessageTable.CONTENT_URI, new String[]{MessageTable.KEY_FILE_TRANSFER_INFO}, 
				selection, selectionArgs, null);
		FileTransferInfo fileTransferInfo = new FileTransferInfo();
		
		if(cursor.moveToFirst()){
			try {
				fileTransferInfo = FileTransferInfo.parseFrom(cursor.getBlob(cursor.getColumnIndexOrThrow(MessageTable.KEY_FILE_TRANSFER_INFO)));
			} catch (InvalidProtocolBufferMicroException e) {
				MTalkLogWriter.e(e);
			} catch (IllegalArgumentException e) {
				MTalkLogWriter.e(e);
			}
		}
		cursor.close();
		return fileTransferInfo;
	}
	
	/**
	 * Thumbnail 전송 정보를 읽어 온다.
	 * @param context
	 * @param messageUuid
	 * @return
	 */
	public static FileTransferInfo getThumbnailTransferInfo(Context context, UUID clientMsgUuid){
		ContentResolver cr = context.getContentResolver();
		String selection;
		String[] selectionArgs;
		selection = MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB+"=? AND "
		+ MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB+"=?";
		selectionArgs = new String[]{String.valueOf(clientMsgUuid.getMostSignificantBits()),
				String.valueOf(clientMsgUuid.getLeastSignificantBits())};
		
		Cursor cursor = cr.query(MessageTable.CONTENT_URI, new String[]{MessageTable.KEY_THUMBNAIL}, 
				selection, selectionArgs, null);
		FileTransferInfo fileTransferInfo = new FileTransferInfo();
		
		if(cursor.moveToFirst()){
			try {
				fileTransferInfo = FileTransferInfo.parseFrom(cursor.getBlob(cursor.getColumnIndexOrThrow(MessageTable.KEY_THUMBNAIL)));
			} catch (InvalidProtocolBufferMicroException e) {
				MTalkLogWriter.e(e);
			} catch (IllegalArgumentException e) {
				MTalkLogWriter.e(e);
			}
		}
		cursor.close();
		return fileTransferInfo;
	}
	
	/**
	 * 유저 메시지 정보를 읽어 온다. // 주의!! 반드시 유저메시지를 담고 있는 메시지에 대해서만 요청
	 * @param context
	 * @param clientMessageUuid
	 * @return
	 */
	public static UserMessage getUserMessage(Context context, UUIDMsg clientMessageUuid){
		ContentResolver cr = context.getContentResolver();
		String selection = MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB+"=? AND "
			+ MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB+"=?";
		String[] selectionArgs = new String[]{
			String.valueOf(GpbSupport.msbOf(clientMessageUuid)), String.valueOf(GpbSupport.lsbOf(clientMessageUuid))};
		Cursor cursor = cr.query(MessageTable.CONTENT_URI, new String[]{MessageTable.KEY_MESSAGE}, 
				selection, selectionArgs, null);
		UserMessage um = new UserMessage();
		if(cursor.moveToFirst()){
			try {
				um = UserMessage.parseFrom(cursor.getBlob(cursor.getColumnIndexOrThrow(MessageTable.KEY_MESSAGE)));
			} catch (InvalidProtocolBufferMicroException e) {
				MTalkLogWriter.e(e);
			} catch (IllegalArgumentException e) {
				MTalkLogWriter.e(e);
			}
		}
		cursor.close();
		return um;
	}
	
	/**
	 * 클라이언트 독립적인 UUID를 얻어온다.
	 * @param context
	 * @param messageUuid
	 * @return
	 */
	public static UUID getClientMessageUuid(Context context, UUIDMsg messageUuid){
		String[] projection = new String[]{ MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB, MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB };
		String select = "(" + MessageTable.KEY_MESSAGE_UUID_MSB + "=? AND "
		+ MessageTable.KEY_MESSAGE_UUID_LSB + "=?)";
		String[] selectionArgs = new String[]{ String.valueOf(GpbSupport.msbOf(messageUuid)), String.valueOf(GpbSupport.lsbOf(messageUuid))}; 
		ContentResolver cr = context.getContentResolver();
		Cursor messageCursor = cr.query(MessageTable.CONTENT_URI, 
				projection, 
				select,
				selectionArgs,
				null);
		
		UUID clientMessageUuid = UUID.randomUUID();
		if(messageCursor.moveToFirst()){
			long clientMessageUuidMsb = messageCursor.getLong(messageCursor.getColumnIndexOrThrow(MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB));
			long clientMessageUuidLsb = messageCursor.getLong(messageCursor.getColumnIndexOrThrow(MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB));
			clientMessageUuid = new UUID(clientMessageUuidMsb, clientMessageUuidLsb);
		}
		messageCursor.close();
		return clientMessageUuid;
	}
	
	
	
	
	/**
	 * 메시지가 존재하는지 확인한다. 존재한다면 false 리턴
	 * @param context
	 * @param messageList
	 * @return
	 */
	public static boolean checkMessage(Context context, UUIDMsg viewUuid, List<Common.Message> messageList){
		ContentResolver cr = context.getContentResolver();
		String where = "";
		for(int i = 0; i < messageList.size(); i++){
			if(i == 0){
				where = "(" + MessageTable.KEY_MESSAGE_UUID_MSB + "=" + GpbSupport.msbOf(messageList.get(i).getMsgUuid())
				+ " AND "
				+ MessageTable.KEY_MESSAGE_UUID_LSB + "=" + GpbSupport.lsbOf(messageList.get(i).getMsgUuid()) + ")";
			}else{
				where = where + " OR " 
				+ "(" + MessageTable.KEY_MESSAGE_UUID_MSB + "=" + GpbSupport.msbOf(messageList.get(i).getMsgUuid())
				+ " AND "
				+ MessageTable.KEY_MESSAGE_UUID_LSB + "=" + GpbSupport.lsbOf(messageList.get(i).getMsgUuid()) + ")";
			}
		}
		boolean checkMessage = true;
		
		Cursor messageCursor = cr.query(MessageTable.CONTENT_URI, new String[]{MessageTable._ID}, 
				where, null, null);
		try{
			Log.i("ATOM", "Exist Message Count : " + messageCursor.getCount());
			if(messageCursor.getCount() > 3){
				checkMessage = false;
			}
		}finally{
			messageCursor.close();
		}
		
		return checkMessage;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	/** 업데이트 Update **/
	
	/**
	 * 새로운 UUID를 받아서 기존의 UUID 를 업데이트 한다.
	 * @param context
	 * @param clientViewUuid 기존의 UUID
	 * @param createViewUuid 업데이트할 UUID
	 */
	public static void updateViewUuid(Context context, UUID clientViewUuid, UUIDMsg createViewUuid){
		ContentValues cv = new ContentValues();
		cv.put(MessageTable.KEY_VIEW_UUID_MSB, GpbSupport.msbOf(createViewUuid));
		cv.put(MessageTable.KEY_VIEW_UUID_LSB, GpbSupport.lsbOf(createViewUuid));
		
		ContentResolver cr = context.getContentResolver();
		cr.update(MessageTable.CONTENT_URI, cv,
				MessageTable.KEY_CLIENT_VIEW_UUID_MSB+"=" 
				+ String.valueOf(clientViewUuid.getMostSignificantBits())
				+ " AND "
				+ MessageTable.KEY_CLIENT_VIEW_UUID_LSB+"=" 
				+ String.valueOf(clientViewUuid.getLeastSignificantBits()), null);
	
	}
	/**
	 * message_status = server_receive 플래그로 바꾸고, uuid_msb,lsb 바꾸기
	 * @param msgRes
	 */
	public static void updateSendAfter(
			Context context,
			UUID clientMsgUuid,
			SendMessageRes msgRes) {
		updateSendAfter(context, clientMsgUuid, MessageStatus.SERVER_RECEIVE, msgRes);
	}
	
	public static void updateSendAfter(Context context,
			UUID clientMsgUuid,
			MessageStatus status,
			SendMessageRes msgRes){
		ContentValues cv = new ContentValues();
		if( msgRes!=null && msgRes.getResponseCode()==Common.SUCCESS ){ 
			cv.put(MessageTable.KEY_MESSAGE_UUID_MSB, GpbSupport.msbOf(msgRes.getMsgUuid()));
			cv.put(MessageTable.KEY_MESSAGE_UUID_LSB, GpbSupport.lsbOf(msgRes.getMsgUuid()));
			cv.put(MessageTable.KEY_MESSAGE_NOTI_UUID_MSB, GpbSupport.msbOf(msgRes.getNotiUuid()));
			cv.put(MessageTable.KEY_MESSAGE_NOTI_UUID_LSB, GpbSupport.lsbOf(msgRes.getNotiUuid()));
			cv.put(MessageTable.KEY_MESSAGE_STATUS, status.ordinal());
			Log.e("ATOM", "Status : " + status.ordinal());
			cv.put(MessageTable.KEY_MESSAGE_TIME, TimeAdapter.getMillisecondFromUUIDMsg(msgRes.getMsgUuid()));
		} else {
			cv.put(MessageTable.KEY_MESSAGE_STATUS, MessageStatus.SERVER_RECEIVE_FAIL.ordinal());
		}
		try{
			String selection = MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB+"=? AND "
			+ MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB+"=?";
			String[] selectionArgs = new String[]{String.valueOf(clientMsgUuid.getMostSignificantBits()),
					String.valueOf(clientMsgUuid.getLeastSignificantBits())};
			ContentResolver cr = context.getContentResolver();
			cr.update(MessageTable.CONTENT_URI, 
					cv, 
					selection, 
					selectionArgs);
		} catch(Exception e) {
			MTalkLogWriter.e(e);
		}
	}
	
	public static void updateMessageStatus(Context context, UUID clientMsgUuid, int status){
		ContentValues cv = new ContentValues();
		cv.put(MessageTable.KEY_MESSAGE_STATUS, status);
		try{
			ContentResolver cr = context.getContentResolver();
			String selection = MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB+"=? AND "
			+ MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB+"=?";
			String[] selectionArgs = new String[]{String.valueOf(clientMsgUuid.getMostSignificantBits()),
					String.valueOf(clientMsgUuid.getLeastSignificantBits())};
			cr.update(MessageTable.CONTENT_URI, cv, selection, selectionArgs);
		}catch(Exception e){
			MTalkLogWriter.e(e);
		}
	}
	
	public static void updateUnreadCount(Context context, ReadMark readMark){
		ContentValues cv = new ContentValues();
		cv.put(MessageTable.KEY_MESSAGE_UNREAD_COUNT, -1);
		try{
			ContentResolver cr = context.getContentResolver();
			String selection = MessageTable.KEY_MESSAGE_UUID_MSB+"=? AND "
			+ MessageTable.KEY_MESSAGE_UUID_LSB+"=?";
			String[] selectionArgs = new String[]{
					String.valueOf(GpbSupport.msbOf(readMark.getMsgUuid())),
					String.valueOf(GpbSupport.lsbOf(readMark.getMsgUuid()))};
			cr.update(MessageTable.CONTENT_URI, cv, selection, selectionArgs);
		}catch(Exception e){
			MTalkLogWriter.e(e);
		}
	}

	/**
	 * 메시지에 FILE_URI(PATH)를 설정한다.
	 * @param context
	 * @param messageUuid
	 * @param path
	 */
	public static void setFileUri(Context context, UUIDMsg messageUuid, Uri uri){
		ContentValues cv = new ContentValues();
		cv.put(MessageTable.KEY_FILE_URI, uri.toString());
		try{
			String where = MessageTable.KEY_MESSAGE_UUID_MSB+"=? AND "
				+ MessageTable.KEY_MESSAGE_UUID_LSB+"=?";
			String[] selectionArgs = new String[]{
					String.valueOf(GpbSupport.msbOf(messageUuid)), String.valueOf(GpbSupport.lsbOf(messageUuid))};
			ContentResolver cr = context.getContentResolver();
			cr.update(MessageTable.CONTENT_URI, cv, 
					where, selectionArgs);
		}catch(Exception e){
			MTalkLogWriter.e(e);
		}
	}
	
	/**
	 * 메시지에 파일 전송 정보를 설정한다.
	 * @param context
	 * @param messageUuid
	 * @param path
	 */
	public static void setFileTransferInfo(Context context, UUID clientMsgUuid, FileTransferInfo info){
		
		ContentValues cv = new ContentValues();
		cv.put(MessageTable.KEY_FILE_TRANSFER_INFO, info.toByteArray());
		
		String where;
		String[] selectionArgs;
		where = MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB+"=? AND "
		+ MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB+"=?";
		selectionArgs = new String[]{String.valueOf(clientMsgUuid.getMostSignificantBits()),
				String.valueOf(clientMsgUuid.getLeastSignificantBits())};
		try{
			ContentResolver cr = context.getContentResolver();
			cr.update(MessageTable.CONTENT_URI, cv, 
					where, selectionArgs);
		}catch(Exception e){
			MTalkLogWriter.e(e);
		}
	}
	
	/**
	 * Thumbnail 전송 정보를 기록
	 * @param context
	 * @param messageUuid
	 * @param path
	 */
	public static void setThumbnailTransferInfo(Context context, UUID clientMsgUuid, FileTransferInfo info){
		ContentValues cv = new ContentValues();
		cv.put(MessageTable.KEY_THUMBNAIL, info.toByteArray());
		
		String where;
		String[] selectionArgs;
		where = MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB+"=? AND "
		+ MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB+"=?";
		selectionArgs = new String[]{String.valueOf(clientMsgUuid.getMostSignificantBits()),
				String.valueOf(clientMsgUuid.getLeastSignificantBits())};
		try{
			ContentResolver cr = context.getContentResolver();
			cr.update(MessageTable.CONTENT_URI, cv, 
					where, selectionArgs);
		}catch(Exception e){
			MTalkLogWriter.e(e);
		}
	}
	
	@Deprecated
	public static void setFileTransferInfo(Context context, UUIDMsg messageUuid, FileTransferInfo info){
		ContentValues cv = new ContentValues();
		cv.put(MessageTable.KEY_FILE_TRANSFER_INFO, info.toByteArray());
		
		String where;
		String[] selectionArgs;
		where = MessageTable.KEY_MESSAGE_UUID_MSB+"=? AND "
		+ MessageTable.KEY_MESSAGE_UUID_LSB+"=?";
		selectionArgs = new String[]{
				String.valueOf(GpbSupport.msbOf(messageUuid)), String.valueOf(GpbSupport.lsbOf(messageUuid))};
		try{
			ContentResolver cr = context.getContentResolver();
			cr.update(MessageTable.CONTENT_URI, cv, 
					where, selectionArgs);
		}catch(Exception e){
			MTalkLogWriter.e(e);
		}
	}
	
	/**
	 * 유저 메시지를 설정한다.
	 * @param context
	 * @param messageUuid
	 * @param path
	 */
	public static void setUserMessage(Context context, UUID clientMsgUuid, UserMessage userMessage){
		ContentValues cv = new ContentValues();
		cv.put(MessageTable.KEY_MESSAGE, userMessage.toByteArray());
		try{
			String select = MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB+"=? AND "
			+ MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB+"=?";
			String[] selectionArgs = new String[]{String.valueOf(clientMsgUuid.getMostSignificantBits()),
					String.valueOf(clientMsgUuid.getLeastSignificantBits())};
			ContentResolver cr = context.getContentResolver();
			cr.update(MessageTable.CONTENT_URI, cv, 
					select, 
					selectionArgs);
		}catch(Exception e){
			MTalkLogWriter.e(e);
		}
	}
	
	/**
	 * 기존의 메시지가 변경될수 있는가? 그렇다면 여기서 업데이트를 해줘야 한다.!
	 * @param context
	 * @param message
	 */
	public static void updateMessage(Context context, Common.Message message){
		// 아직은 할일이 없어 보인다. 2011-05-08
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	/** 삭제 **/
	public static void deleteMsgWhereView(Context context, long messageNotiUuidMsb, long messageNotiUuidLsb)
	{
		ContentResolver cr = context.getContentResolver();
		StringBuilder where = new StringBuilder();
		where.append(MessageTable.KEY_MESSAGE_NOTI_UUID_MSB).append("=? AND ").append(MessageTable.KEY_MESSAGE_NOTI_UUID_LSB).append("=?");
		String[] selectionArgs = {String.valueOf(messageNotiUuidMsb), String.valueOf(messageNotiUuidLsb)};
		cr.delete(MessageTable.CONTENT_URI, where.toString(), selectionArgs);
	}
	
	public static void deleteMsgWhereView(Context context, UUID clientMsbUuid)
	{
		ContentResolver cr = context.getContentResolver();
		StringBuilder where = new StringBuilder();
		where.append(MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB).append("=? AND ").append(MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB).append("=?");
		String[] selectionArgs = {String.valueOf(clientMsbUuid.getMostSignificantBits()), String.valueOf(clientMsbUuid.getLeastSignificantBits())};
		cr.delete(MessageTable.CONTENT_URI, where.toString(), selectionArgs);
	}
	
	public static void deleteAllMessage(Context context)
	{
		ContentResolver cr = context.getContentResolver();
		cr.delete(MessageTable.CONTENT_URI, null, null);
	}
	
	
	
	
	
	
	
	/** 추가 내용 **/

	/**
	 *  받은 메시지를 업데이트 하기 위한 Values를 설정한다.
	 */
	private static ContentValues setContentValuesForGetMessages(
			UUID clientViewUuid,
			Message message, 
			MessageProperty property,
			Uri fileUri,
			UUID clientMsgUuid){
		if(clientMsgUuid == null){
			clientMsgUuid = UUID.randomUUID();
		}
		ContentValues cv = new ContentValues();
		cv.put(MessageTable.KEY_CLIENT_VIEW_UUID_MSB, clientViewUuid.getMostSignificantBits());
		cv.put(MessageTable.KEY_CLIENT_VIEW_UUID_LSB, clientViewUuid.getLeastSignificantBits());
		cv.put(MessageTable.KEY_VIEW_UUID_MSB, GpbSupport.msbOf(message.getViewUuid()));
		cv.put(MessageTable.KEY_VIEW_UUID_LSB, GpbSupport.lsbOf(message.getViewUuid()));
		cv.put(MessageTable.KEY_CLIENT_MESSAGE_UUID_MSB, clientMsgUuid.getMostSignificantBits());
		cv.put(MessageTable.KEY_CLIENT_MESSAGE_UUID_LSB, clientMsgUuid.getLeastSignificantBits());
		cv.put(MessageTable.KEY_MESSAGE_UUID_MSB, GpbSupport.msbOf(message.getMsgUuid()));
		cv.put(MessageTable.KEY_MESSAGE_UUID_LSB, GpbSupport.lsbOf(message.getMsgUuid()));
		cv.put(MessageTable.KEY_MESSAGE_NOTI_UUID_MSB, GpbSupport.msbOf(message.getNotiUuid()));
		cv.put(MessageTable.KEY_MESSAGE_NOTI_UUID_LSB, GpbSupport.lsbOf(message.getNotiUuid()));
		if(message.getType()==Common.MSG_TYPE_USER_MSG){
			cv.put(MessageTable.KEY_MESSAGE_OBJECT_TYPE, MessageTable.MessageObjectType.USER.getCode());
			UserMessage um = message.getUserMassage();
			cv.put(MessageTable.KEY_MESSAGE, um.toByteArray());
			// 첨부파일이 있을경우.
			if(um.hasAttachFile()){
				FileKey fileKey = um.getAttachFile();
				switch(fileKey.getFileType()){
					case Common.FT_IMG:
						if(fileUri != null){
							cv.put(MessageTable.KEY_FILE_URI, fileUri.getPath());
						}
						break;
					case Common.FT_AUDIO:
//						fileKey.get
						break;
					case Common.FT_VIDEO:
						break;
				}
			}
			if(um.hasSenderUuid()){
				if((GpbSupport.msbOf(um.getSenderUuid()) == GpbSupport.msbOf(GlobalPreferences.getUserUUID())) 
						&& (GpbSupport.lsbOf(um.getSenderUuid()) == GpbSupport.lsbOf(GlobalPreferences.getUserUUID()))){					
					cv.put(MessageTable.KEY_MESSAGE_STATUS, MessageTable.MessageStatus.SERVER_RECEIVE.ordinal());
					cv.put(MessageTable.KEY_SEND_MESSAGE, MessageTable.SendMessage.YES.ordinal());
				}else{
					cv.put(MessageTable.KEY_MESSAGE_STATUS, MessageTable.MessageStatus.CLIENT_RECEIVE.ordinal());
					cv.put(MessageTable.KEY_SEND_MESSAGE, MessageTable.SendMessage.NO.ordinal());
				}
			}else{			
				cv.put(MessageTable.KEY_MESSAGE_STATUS, MessageTable.MessageStatus.CLIENT_RECEIVE.ordinal());
				cv.put(MessageTable.KEY_SEND_MESSAGE, MessageTable.SendMessage.NO.ordinal());
			}
		} else if(message.getType()==Common.MSG_TYPE_SYSTEM_MSG){
			cv.put(MessageTable.KEY_MESSAGE_OBJECT_TYPE, MessageTable.MessageObjectType.SYSTEM.getCode());
			cv.put(MessageTable.KEY_MESSAGE, message.getSystemMessage().toByteArray());
			cv.put(MessageTable.KEY_MESSAGE_STATUS, MessageTable.MessageStatus.CLIENT_RECEIVE.ordinal());
			cv.put(MessageTable.KEY_SEND_MESSAGE, MessageTable.SendMessage.NO.ordinal());
		} else if(message.getType()==Common.MSG_TYPE_CONTROL_MSG){
			cv.put(MessageTable.KEY_MESSAGE_OBJECT_TYPE, MessageTable.MessageObjectType.CONTROL.getCode());
			cv.put(MessageTable.KEY_MESSAGE, message.getControlMessage().toByteArray());
			cv.put(MessageTable.KEY_MESSAGE_STATUS, MessageTable.MessageStatus.CLIENT_RECEIVE.ordinal());
			cv.put(MessageTable.KEY_SEND_MESSAGE, MessageTable.SendMessage.NO.ordinal());
		}
		
		// TIME-STAMP
		UUID msgUuid = new UUID(GpbSupport.msbOf(message.getMsgUuid()), 
				GpbSupport.lsbOf(message.getMsgUuid()));
		cv.put(MessageTable.KEY_MESSAGE_TIME, TimeAdapter.getMillisecondFromUUID(msgUuid));
		
		if( property!=null ) cv.put(MessageTable.KEY_MESSAGE_PROPERTY, property.ordinal());
		if( fileUri!= null ) cv.put(MessageTable.KEY_FILE_URI, fileUri.toString());
		return cv;
	}
}
